package at.codebase.web.templates.message;

import static at.codebase.web.util.i18n.I18NFactory.i18n;

import java.util.ArrayList;

import org.json.simple.JSONObject;

import at.codebase.db.dao.EItemDao;
import at.codebase.db.entities.EItem;
import at.codebase.db.entities.EMessageExt;
import at.codebase.db.entities.EMessageExt.UserExt;
import at.codebase.security.SecureStringBuilder;
import at.codebase.security.SecurityUtils;
import at.codebase.web.servlets.user.UserMessages.ItemConversationExt;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.api.ApiPartnerCalls;
import at.codebase.web.util.i10n.L10N;
import at.codebase.web.util.i18n.I18NLocale;
import at.codebase.web.util.template.Template;
import at.codebase.web.util.template.TemplateEngine;

import com.googlecode.objectify.Key;

/**
 * 
 * @author Lukas Pfeifhofer <lukas.pfeifhofer@devlabs.pro>
 *
 */
public class ItemConversationExtTemplate extends Template {

	private static String TEMPLATE_URL = "user/message/item_message_container_ext.html";
	private static String MESSAGE_TEMPLATE_URL = "user/message/item_message.html";

	public ItemConversationExtTemplate(RequestInformation requestInfo, ItemConversationExt conversation) {
		super(TemplateEngine.getTemplateContent(TEMPLATE_URL));
		init(requestInfo, conversation);
	}

	private void init(RequestInformation requestInfo, ItemConversationExt conversation) {
		I18NLocale loc = requestInfo.getLocale();
		UserExt conPartner = conversation.partner;

		String itemTitel;
		String itemPrice;
		
		//if(conversation.item.getImageKeys().size() > 0){
		//	setText("imageUrl", "/service/image?id="+conversation.item.getImageKeys().get(0).getId()+"&w=40&h=40");
		//}else{
		setText("imageUrl", "/images/no_image_available.png");
		//}
		Key<EItem> itemKey = Key.create(conversation.item);

		if(itemKey.getRaw().getAppId().equals(conPartner.getPartner().getKey().getRaw().getAppId())){
			//OWN Item
			EItem item = EItemDao.getItemById(new Long(itemKey.getId()));
			if(item.getImageKeys().size() > 0){
				setText("imageUrl", "/service/image?id="+item.getImageKeys().get(0).getId()+"&w=40&h=40");
			}
			itemTitel = item.getTitle();
			itemPrice = item.getPrice()+" USD";
		}else{
			//Other Item
			JSONObject item = ApiPartnerCalls.getItem(conPartner.getPartner().get(), String.valueOf(itemKey.getId()));
			if(item != null && item.get("success").equals(new Boolean(true))){
				itemTitel = (String) item.get("title");
				itemPrice = (String) item.get("price");	
			}else{
				itemTitel = "(Currently not available)";
				itemPrice = "n/A";
			}
			System.out.println(item);
		}
			
			
		setHTML("itemId", conversation.item);//conversation.item.getId().toString());
		setHTML("itemTitel", itemTitel);
		setHTML("itemPrice", itemPrice);
		
		setText("partnerId", new Long(conPartner.getPartner().getKey().getId()).toString());
		setText("extUserId", conPartner.getUserId());
		setText("extUserName", conPartner.getUserName());
		setText("extConversationId", conversation.conversationId);
		setText("recipientId", conPartner.getUserId());
		
		SecureStringBuilder sb = new SecureStringBuilder();
		sb.appendSecure(conPartner.getUserName());
		sb.appendInsecure(" (<a target=\"_blank\" href=\""+conPartner.getPartner().get().getAppUrl()+"\">"+conPartner.getPartner().get().getAppName()+"</a>)");
		
		setHTML("messagePartnerNickname", sb.toString());
		setText("messagesTotal", String.valueOf(conversation.messages.size()));
		if (conversation.unreadIds.size() > 0) {
			setHTML("messagesUnread", "<b>(" + conversation.unreadIds.size() + ")</b>");
			String unreadIds = conversation.unreadIds.get(0).toString();
			for(int i = 1; i < conversation.unreadIds.size(); i++){
				unreadIds += "," + conversation.unreadIds.get(i) ;
			}
			setText("unreadIds", unreadIds);
		}
		
		ArrayList<Template> messageTemplates = new ArrayList<Template>();

		Long lastPartner = null;
		
		for (EMessageExt message : conversation.messages) {
			Template messageTemplate = TemplateEngine.getTemplate(MESSAGE_TEMPLATE_URL);
			
			if(message.getAddressor() != null){
				messageTemplate.setText("addressorNickname", i18n(loc).string("userMessages_message_adressor"));
				messageTemplate.setText("messageStyleClass", "userMessagesPrivateMessage");
			}else{
				lastPartner = message.getId();
				messageTemplate.setText("addressorNickname", conPartner.getUserName());
				
				messageTemplate.setText("messageStyleClass", "userMessagesPrivateMessagePartner");
				messageTemplate.setHTML("image", "<img src=\"/images/icons/email_open.png\">");
			}
			
			String safeDescriptionText =  SecurityUtils.sanatize(message.getText());
			messageTemplate.setHTML(
					"timeSend",
					i18n(loc).string("userMessages_message_timeDate",
							L10N.formatDate(loc, message.getTimeSend()),
							L10N.formatTime(loc, message.getTimeSend())));
			messageTemplate.setHTML("messageContent", safeDescriptionText.replace("\n", "<br>"));
			messageTemplate.setText("messageId", message.getId().toString());
			messageTemplates.add(messageTemplate);
		}
		
		if (lastPartner != null) {
			setText("jumpId", lastPartner.toString());
		}
		
		
		setTemplates("messageList", messageTemplates);
	}
	
}